package com.study.demo01.controller;

import com.study.demo01.dto.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "RegisterServlet",urlPatterns = "/register.do")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收参数
       String username =  request.getParameter("username");
       String pwd =  request.getParameter("pwd");
        String sex = request.getParameter("sex");
        User user = new User(username,pwd,Integer.parseInt(sex));
       //把注册用户存储起来
       ServletContext sc =  request.getServletContext();
       List<User> users = (List<User>) sc.getAttribute("users");
        //把user存到缓存中(application)
        users.add(user);
        sc.setAttribute("users",users);
        request.setAttribute("tip","注册成功!请登录");
        request.getRequestDispatcher("login.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
